require 'sequel/sqlite'

DB = Sequel.open 'sqlite:/'

DB.create_table :items do
  integer :id, :primary_key => true, :auto_increment => true
  text :name
  decimal :price
end

class DatasetExtenderModule < Module
  def subset(*args, &block)
    name = args.shift
    define_method(name) do
      filter(*args, &block)
    end
  end
end

class Sequel::Dataset
  def extend(mod = nil, &block)
    super(mod || Module.new(&block))
    self
  end
end

class Sequel::Model
  def self.subset(*args, &block)
    dataset.extend do
      name = args.shift
      define_method(name) do
        filter(*args, &block)
      end
    end
  end
end

class Item < Sequel::Model(:items)
  subset(:cheap) {price < 25}
end

Items = Item.dataset.extend do
end

# Items = DB[:items].extend do
#   record_class :item do
#     belongs_to Category
#   end
#   subset(:cheap) {price < 25}
# end
# 
100.times {|i| Items << {:name => "item#{i}", :price => rand(1000) / 30}}

module Enumerable
  alias_method :orig_select, :select
  alias_method :orig_reject, :reject
  def select(hash = nil, &block)
    if hash
      orig_select do |i|
        hash.inject(true) {|m, kv| m && (i.send(kv[0]) == kv[1])}
      end
    else
      orig_select(&block)
    end
  end
  
  def reject(hash = nil, &block)
    if hash
      orig_reject do |i|
        hash.inject(true) {|m, kv| m && (i.send(kv[0]) == kv[1])}
      end
    else
      orig_reject(&block)
    end
  end
end
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      